<!-- 商品属性参数列表 -->
<template>
  <div class="attrList sys-content">
    <el-page-header title="关闭" icon="CloseBold" @back="doClose">
      <template #content>
        <el-icon><SetUp /></el-icon>
        商品{{type ? '参数' : '属性'}}列表
      </template>
      <template #extra>
        <el-button type="primary" icon="Plus" @click="toAdd">新增</el-button>
      </template>
    </el-page-header>
    <el-table ref="table" :data="dataList" v-loading="loading" element-loading-text="拼命加载中" max-height="493" row-key="id" border>
      <el-table-column label="编号" type="index" align="center" width="100"></el-table-column>
      <el-table-column :label="`商品${type ? '参数' : '属性'}名称`" prop="name" align="center"></el-table-column>
      <el-table-column :label="`可选${type ? '参数' : '属性'}`" prop="attributeValues" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="{row}">
          <el-button type="primary" icon="Edit" link @click="toUpdate(row.attributeId)">修改</el-button>
          <el-divider direction="vertical" />
          <el-button type="danger" icon="Delete" link @click="doDelete(row.attributeId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 新增，修改弹窗 -->
    <el-dialog 
      v-model="show" 
      :title="form.attributeId ? `商品${type ? '参数' : '属性'}-修改` : `商品${type ? '参数' : '属性'}-新增`"
      center 
      width="33%" 
      draggable 
      @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="90">
        <el-form-item :label="`${type ? '参数' : '属性'}名称:`" prop="name" required>
          <el-input v-model="form.name" :placeholder="`请输入商品${type ? '参数' : '属性'}名称`" clearable/>
        </el-form-item>
        <el-form-item :label="`商品${type ? '参数' : '属性'}:`" prop="valueList" required>
          <el-button v-if="type === 0" type="primary" size="default" @click="doCondition(true)">
            新增{{type ? '参数' : '属性'}}
          </el-button>
          <el-table :data="form.valueList" max-height="493" row-key="id" border>
            <el-table-column label="编号" type="index" align="center" width="100"></el-table-column>
            <el-table-column :label="type ? '参数' : '属性'" prop="attrName" align="center">
              <template #default="{row}">
                <el-input v-model="row.attributeValue" :placeholder="`请输入${type ? '参数' : '属性'}`" clearable/>
              </template>
            </el-table-column>
            <el-table-column v-if="type === 0" label="操作" align="center" width="80">
              <template #default="{$index}">
                <el-button type="danger" icon="Delete" link @click="doCondition(false, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="attrList">
  import { cudGoodsAttrParamsApi, getGoodsAttrParamsApi, getGoodsAttrParamsInfoApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, watch } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties

  // 定义父组件传入的值
  const props = defineProps({
    attributeCategoryId: {
      type: String,
      default: '',
      required: true
    },
    merchantId: {
      type: String,
      default: '',
      required: true
    },
    type: {
      type: Number,
      default: 0,
      required: true
    }
  })
  // 定义传值给父组件数据方法
  const emits = defineEmits(['close'])
  
  const formRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    dataList: [],
    form: {
      attributeId: '',
      attributeCategoryId: '',
      merchantId: '',
      type: 0,
      name: '',
      valueList: []
    },
    rules: {
      name: [{ required: true, message: '请输入名称', trigger: ['blur', 'change'] }],
      valueList: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error(`请添加商品${props.type ? '参数' : '属性'}`))
            } else {
              callback()
            }
          } 
        }
      ]
    }
  })
  let {loading, show, dataList, form, rules} = toRefs(currentData)

  watch(() => props, (newVal) => {
    currentData.form.attributeCategoryId = props.attributeCategoryId
    currentData.form.merchantId = props.merchantId
    currentData.form.type = props.type
    load()
  }, {
    immediate: true, // 立即监听
    deep: true
  })

  // 查询
  function load() {
    currentData.loading = true
    getGoodsAttrParamsApi(props.type, props.attributeCategoryId).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.attributeId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.attributeId ? '修改' : '新增'}`)
          cudGoodsAttrParamsApi(`${currentData.form.attributeId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load()
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 添加或删除属性/列表项
  function doCondition(type, index) {
    if(type) {
      currentData.form.valueList.push({ attributeValue: '' })
    } else {
      currentData.form.valueList.splice(index, 1)
    }
  }

  // 删除
  function doDelete(attributeId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      cudGoodsAttrParamsApi('delete', { id: attributeId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load()
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  function toUpdate(attributeId) {
    getGoodsAttrParamsInfoApi(attributeId).then(res => {
      if(res.code === '200') {
        currentData.form.attributeId = res.data.attributeId
        currentData.form.name = res.data.name
        currentData.form.valueList = res.data.attributeValueList
        currentData.show = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  function doClose() {
    emits('close')
  }

  function toAdd() {
    currentData.form.attributeId = ''
    currentData.form.name = ''
    currentData.form.valueList = currentData.form.type === 1 ? [{ attributeValue: '' }] : []
    currentData.show = true
  }

  function resetForm() {
    formRef.value.resetFields()
  }
</script>

<style lang="less" scoped>
.attrList{
  :deep(.el-page-header){
    margin: 15px 0;
    .el-page-header__content{
      display: flex;
      align-items: center;
    }
  }
  :deep(.el-dialog){
    .el-form-item{
      .el-table{
        margin-top: 10px;
      }
      .el-input{
        width: 250px;
      }
    }
  }
}
</style>